<template>
	<view class="normal-login-container">
		<view class="top_img" style="font-size: 35px;">
			<view class="">
				您好，
			</view>
			<view class="">
				欢迎使用智慧订餐
			</view>
		</view>

		<view class="login-form-content">
			<view class="input-item flex align-center">
				<!-- <view class="iconfont icon-user icon"></view> -->
				<view class="label">账号</view>
				<input v-model="loginForm.username " style="height: 45px;" class="input" type="text" placeholder="请输入账号" maxlength="30" />
				<view class="u-demo-block__content">
				</view>
			</view>
			<view class="input-item flex align-center">
				<view class="label">密码
				</view>
				<input v-model="passwords" @input="inpupawss"  style="height: 45px;" class="input" placeholder="请输入密码" maxlength="30" />
				 <!-- <u--input
				    placeholder="请输入内容"
				    border="surround"
					type="password"
				    v-model="loginForm.password"
				    @change="change"
				  ></u--input> -->
			</view>
		
			<view class="" style="display: flex;justify-content: space-between;align-items: flex-start">
				<u-radio-group v-model="radiovalue" placement="row" @change="gsroupChange" size="30">
					<u-radio  activeColor="#0EB275" :customStyle="{marginBottom: '8px',marginRight:'50rpx',transform:'scale(1)'}"
						v-for="(item, index) in radiolist" :key="index" :label="item.name" :name="item.name">
					</u-radio>
				</u-radio-group>
				<view class="flex align-center">
					<!-- 勾选框 -->
					  <u-checkbox-group
					            v-model="isRememberPwd"
					            placement="column"
					        >
								<u-checkbox 
									activeColor="#0EB275" 
									size="28px" 
									style="margin-right: 12rpx;"
								></u-checkbox>
					        </u-checkbox-group>

					<!-- 文字 -->
					<text style="font-size: 28rpx; color: #333;">记住密码</text>
				</view>
			</view>
			<view class="remember-password flex align-center justify-between" style="margin: 20rpx 0;">
							
							<!-- 可选：忘记密码（按需添加） -->
						
						</view>
			<view class="action-btn">
				<button open-type="subscribe" @click="handleLogin"
					class="login-btn cu-btn block bg-green lg round ">登录</button>
				<!-- <button @click="quickLogin" class="login-btn cu-btn block bg-blue lg round">手机号快捷登录</button> -->
				<!-- <button open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber"
					class="login-btn cu-btn block bg-blue lg round">手机号快捷登录</button>
				<button open-type="getUserInfo" @click="getUserProfile"
					class="login-btn cu-btn block bg-blue lg round">登录</button> -->
			</view>
			<!-- 			<view class="reg text-center" v-if="register">
				<text class="text-grey1">没有账号？</text>
				<text @click="handleUserRegister" class="text-blue">立即注册</text>
			</view>
			<view class="xieyi text-center">
				<text class="text-grey1">登录即代表同意</text>
				<text @click="handleUserAgrement" class="text-blue">《用户协议》</text>
				<text @click="handlePrivacy" class="text-blue">《隐私协议》</text>
			</view> -->
		</view>

	</view>
</template>

<script>
	import config from '@/config'
	import store from "@/store"
	const appid = config.appid
	import {
		getCodeImg,
		getOpenidAPI
	} from '@/api/login'

	export default {
		data() {
			return {
								isRememberPwd: false, // 是否勾选"记住密码"
				passwords:"",
				openidInfo: {
					openid: "",
					sessionKey: ""
				},
				tips: '',
				// 基本案列数据
				radiolist: [{
						name: '员工',
						type: 1,
						disabled: false
					},
					{
						name: '管理员',
						type: 2,
						disabled: false
					}
				],
				// u-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中
				radiovalue: '员工',
				codeUrl: "",
				captchaEnabled: true,
				// 用户注册开关
				register: false,
				globalConfig: getApp().globalData.config,
				loginForm: {
					// nickname: "",
					username: "",
					password: "",

					type: 1
					// code: "",
					// uuid: "",
					// mobile: '',
					// verificationCode: ''

				},
				loginCode: '',
				countNumber:0,
				rememberKey: 'smartOrderLoginInfo'
			}
		},
		created() {
			// console.log('vue');
			// console.log(uni.$u.config.v);
			this.getCode()
			this.getAppCode() 
this.initRememberPwd()
		},
		methods: {
				initRememberPwd() {
					try {
						// 从本地缓存读取登录信息
						let rememberInfos = uni.getStorageSync(this.rememberKey)
						let rememberInfo = ""
						if(rememberInfos){
							rememberInfo = JSON.parse(rememberInfos)
						}
						if (rememberInfo && rememberInfo.username && rememberInfo.password) {
							// 自动填充账号密码
							this.loginForm.username = rememberInfo.username
							this.loginForm.password = rememberInfo.password
							// 自动勾选"记住密码"
							this.isRememberPwd = [""]
							// 同步密码的星号显示
							this.passwords = '*'.repeat(rememberInfo.password.length)
						}
					} catch (e) {
						console.error('读取记住密码缓存失败：', e)
					}
				},
			inpupawss(val){
				if(val.detail.value == 1){
					// this.countNumber = 0;
					this.loginForm.password = ""
				}
				
				// console.log(val.detail.value)
			
				
				if(val.detail.value.length - this.loginForm.password.length > 1){
					this.loginForm.password += val.detail.value.slice(-(val.detail.value.length - this.loginForm.password.length))
				}else{
					if(val.detail.value.length > this.loginForm.password.length){
						this.loginForm.password += val.detail.value.slice( -1);
					}else if(val.detail.value.length < this.loginForm.password.length){
						console.log(val.detail.value.length)
						this.loginForm.password = this.loginForm.password.slice(0, val.detail.value.length);
					}
				}
				
				console.log(this.loginForm.password)
				
				
				let a = "";
				for (var i = 0; i < val.detail.value.length; i++) {
					a += "*"
					
				}
				this.passwords = a;
			},

			gsroupChange(e) {
				// console.log(e)
				if (e == '员工') {
					this.loginForm.type = 1
				} else {
					this.loginForm.type = 2
				}
			},
			// radioChange(e) {
			// 	console.log(e)
			// },
			// async getUserProfile() {
			// 	const ress = await uni.getUserProfile({
			// 		desc: '登录',
			// 		success: (res) => {
			// 			console.log(res)
			// 		},
			// 		fail: (res) => {
			// 			console.log(res)
			// 		}

			// 	})
			// 	console.log(ress);
			// },
			// async onGetPhoneNumber(e) {

			// 	const {
			// 		encryptedData,
			// 		iv,
			// 		errMsg,
			// 		code
			// 	} = e.detail;
			// 	if (errMsg !== 'getPhoneNumber:ok') {
			// 		uni.showToast({
			// 			title: '授权失败',
			// 			icon: 'none'
			// 		});
			// 		return;
			// 	}
			// 	// 拿到加密数据和iv
			// 	// 发送到后端解密并登录
			// 	const res = await uni.request({
			// 		url: 'https://你的后端域名/api/wx-login',
			// 		method: 'POST',
			// 		data: {
			// 			code: this.loginCode, //openid和手机号绑定到一块
			// 			// code,
			// 			encryptedData,
			// 			iv,
			// 		},
			// 	});

			// 	if (res.data.success) {
			// 		uni.setStorageSync('token', res.data.token); // 保存登录态
			// 		uni.reLaunch({
			// 			url: '/pages/index/index'
			// 		}); // 跳转首页
			// 	} else {
			// 		uni.showToast({
			// 			title: '登录失败',
			// 			icon: 'none'
			// 		});
			// 	}
			// },

			async getAppCode() {
				const res = await uni.login()
				if (res && res.length > 0) {
					this.loginCode = res[1].code;
					this.getOpenId()
				}
			},
			async getOpenId() {
				let obj = {
					appId: appid,
					code: this.loginCode
				}
				try {
					const res = await getOpenidAPI(obj)
					this.openidInfo = res.data

				} catch (error) {} finally {}
			},
			// codeChange(text) {
			// 	this.tips = text;
			// },
			// getCodeNum() {
			// 	console.log(this.$refs.uCode.canGetCode);
			// 	if (this.$refs.uCode.canGetCode) {
			// 		// 模拟向后端请求验证码
			// 		uni.showLoading({
			// 			title: '正在获取验证码'
			// 		})
			// 		setTimeout(() => {
			// 			// uni.hideLoading();
			// 			// 这里此提示会被this.start()方法中的提示覆盖
			// 			uni.$u.toast('验证码已发送');
			// 			// 通知验证码组件内部开始倒计时
			// 			this.$refs.uCode.start();
			// 		}, 2000);
			// 	} else {
			// 		uni.$u.toast('倒计时结束后再发送');
			// 	}
			// },
			end() {
				uni.$u.toast('倒计时结束');
			},
			start() {
				uni.$u.toast('倒计时开始');
			},
			// 用户注册
			handleUserRegister() {
				this.$tab.redirectTo(`/pages/register`)
			},
			// 隐私协议
			handlePrivacy() {
				let site = this.globalConfig.appInfo.agreements[0]
				this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
			},
			// 用户协议
			handleUserAgrement() {
				let site = this.globalConfig.appInfo.agreements[1]
				this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
			},
			// 获取图形验证码
			getCode() {
				getCodeImg().then(res => {
					this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
					if (this.captchaEnabled) {
						this.codeUrl = 'data:image/gif;base64,' + res.img
						this.loginForm.uuid = res.uuid
					}
				})
			},
			// 登录方法
			async handleLogin() {

				console.log('开始登录了')

				if (this.loginForm.username === "") {
					this.$modal.msg("请输入账号")
				} else if (this.loginForm.password === "") {
					this.$modal.msg("请输入密码")
				}
				// else if (this.loginForm.code === "" && this.captchaEnabled) {
				// 	this.$modal.msg("请输入验证码")
				// }
				else {
					if (!uni.getStorageSync('message')) {  
						// #ifdef MP-WEIXIN
						uni.requestSubscribeMessage({
							tmplIds: ['zXV87J2fKabL263BRvLj2kYmuYXQae5sKSFlDOcUnGI','dnpokd8368JGWQsBJarfLCKWHmojjTfusNAyTzM_aC0','Nnvg0DY-BL9rPhD1yioe0-iELKsFh_Ji6bZExgiLZl4'], //微信公众平台模板ID
							success: (res) => {
								if (res.errMsg === 'requestSubscribeMessage:ok') {
									uni.setStorageSync('message', true)
									this.$modal.loading("登录中，请耐心等待...")
									this.pwdLogin()
								}
							}
						})
						// this.pwdLogin()
						// return
						// #endif
						// #ifdef H5
						this.$modal.loading("登录中，请耐心等待...")
						this.pwdLogin()
						// #endif

					}
					this.$modal.loading("登录中，请耐心等待...")
					this.pwdLogin()

				}
			},
			// 密码登录
			async pwdLogin() {
				let obj = {
					...this.loginForm,
					...this.openidInfo
				}
				// console.log(obj);
				// return
				this.$store.dispatch('Login', obj).then((result) => {
					console.log
					
					this.$modal.closeLoading()
					this.loginSuccess()
				}).catch(() => {
					
					// if (this.captchaEnabled) {
					// 	this.getCode()
					// }
				})
			},
			// 登录成功后，处理函数
			loginSuccess(result) {
				// 设置用户信息
				this.$store.dispatch('GetInfo').then(res => {
					// this.$tab.reLaunch('/pages/index')
					// 存储员工和管理员选择类型，用于后续切换退出登录判断闪频问题
					uni.setStorageSync('isLoginType', this.loginForm.type) 
					console.log(this.isRememberPwd)
					if (this.isRememberPwd.length > 0) {
							// 勾选：存储账号密码到本地缓存（永久有效，除非手动清除）
							const rememberInfo = {
								username: this.loginForm.username,
								password: this.loginForm.password,
								saveTime: new Date().getTime() // 可选：记录存储时间，后续可加过期逻辑
							}
							uni.setStorageSync(this.rememberKey, JSON.stringify(rememberInfo))
						} else {
							// 未勾选：清除本地缓存中的密码
							uni.removeStorageSync(this.rememberKey)
						}
					const role = 'user'
					if (this.loginForm.type == '1') {
						uni.redirectTo({
							url: '/pages/index'
						}) // 用户端首页

					} else {
						uni.redirectTo({
							url: '/subpackages/admin/pages/index/index'
						})

					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #ffffff;
	}
	
	::v-deep .uni-input-input{
		font-size: 40rpx;
		height: 40px;
	}
	::v-deep .uni-input-placeholder {
		font-size: 40rpx;
	}
	
	::v-deep .u-icon{
		.u-icon__icon{
			font-size: 40rpx !important;
		}
	}

	.normal-login-container {
		background-image: url('https://beihai-food.oss-cn-beijing.aliyuncs.com/452.png');
		width: 100%;
		// padding-top: 120rpx;
		height:100%;
		background-size: cover;
		background-repeat: no-repeat;

		.title {}


		.logo-content {
			width: 100%;
			font-size: 21px;
			text-align: center;
			padding-top: 15%;

			image {
				border-radius: 4px;
			}

			.title {
				margin-left: 10px;
			}
		}
        // 磨砂效果样式
		// .login-form-content::before {
		// 	content: '';
		// 	position: absolute;
		// 	width: 100%;
		// 	height: 200rpx;
		// 	top: 0;
		// 	left: 0;
		// 	right: 0;
		// 	bottom: 0;
		// 	background: rgba(255, 255, 255, 0.23);
		// 	border-radius: 20px 20px 0px 0px;
		// 	backdrop-filter: blur(10px);
		// 	// z-index: -1;
		// }

		.login-form-content {
			position: relative;
			top: -30rpx;
			border-radius: 20px 20px 0px 0px;
			/* 纯白 */
			// border: 1px solid #FFFFFF;
			padding: 140rpx 60rpx 60rpx;
			width: 100%;

			.input-item {
				.label {
					font-size: 40rpx;
					width: 120rpx;
					color: #323232;
				}

				border-bottom: 1px solid rgba(0, 0, 0, 0.05);
				;
				margin: 20px auto;
				// background-color: #f5f6f7;
				height: 45px;
				// border-radius: 20px;

				.icon {
					font-size: 38rpx;
					margin-left: 10px;
					color: #999;
				}

				.input {
					flex: 1;
					// width: 100%;
					font-size: 20px;
					line-height: 40px;
					text-align: left;
					// padding-left: 15px;
				}

			}

			.login-btn {
				// background: linear-gradient(270deg, #2C84FB 0%, rgba(44, 132, 251, 0.42) 100%);
				margin-bottom: 30rpx;
				// margin-top: 40px;
				height: 70rpx;
			}

			.reg {
				margin-top: 15px;
			}

			.xieyi {
				color: #333;
				margin-top: 20px;
			}

			.login-code {
				height: 38px;
				float: right;

				.login-code-img {
					height: 38px;
					position: absolute;
					margin-left: 10px;
					width: 200rpx;
				}
			}
		}
	}

	.top_img {
		padding: 260rpx 60rpx;
		width: 100%;
		height: 520rpx;
		background-size: cover;
		background-repeat: no-repeat;
		font-size: 36rpx;
		font-weight: 500;
	}

	.u-page__code-text {
		color: $uni-color-primary;
	}

	.action-btn {
		margin-top: 80rpx;
	}
</style>